#!/bin/bash

# shellcheck source=meta-facebook/meta-harma/recipes-phosphor/state/phosphor-state-manager/power-cmd
source /usr/libexec/phosphor-state-manager/power-cmd

# Check SGPIO validity
if ! check_valid_sgpio; then
    exit 0
fi

# Sync Led status to on
systemctl start obmc-led-group-start@power_on.service


# Checking and Syncing power policy.
# Get current host state
current_state=$(busctl get-property \
    xyz.openbmc_project.State.Host0 \
    /xyz/openbmc_project/state/host0 \
    xyz.openbmc_project.State.Host \
    CurrentHostState | awk '{print $2}' | tr -d '"')

# Exit if host is already transitioning to running
if [ "$current_state" = "xyz.openbmc_project.State.Host.HostState.TransitioningToRunning" ]; then
    exit 0
fi

# List of services that block power_on_sync
block_services=(
    host-poweron@0.service
    host-powerreset@0.service
)

# Exit if any blocking service is not inactive
for svc in "${block_services[@]}"; do
    if [ "$(systemctl is-active "$svc")" != "inactive" ]; then
        exit 0
    fi
done

# Safe to power on
# Wait 3 seconds, checking every second
power_on_sync 3 1

exit 0
